package com.qing.reflection;

import java.lang.annotation.*;
import java.lang.reflect.Field;

//通过反射来操作注解
public class GetAnnotationByReflection {
    public static void main(String[] args) throws Exception {
        Class c = Class.forName("com.qing.reflection.People");

        //获取类上的注解
        Annotation[] annotations = c.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println(annotation);
        }

        //获取类注解上的value值
        TableNameLx annotation = (TableNameLx) c.getAnnotation(TableNameLx.class);
        System.out.println(annotation.value());

        //获取类中指定列的注解值
        Field age = c.getDeclaredField("age");
        FieldLx fieldLx = age.getAnnotation(FieldLx.class);
        System.out.println(fieldLx.len());
        System.out.println(fieldLx.type());
        System.out.println(fieldLx.name());

    }
}

@TableNameLx("db_people")
class People {

    @FieldLx(name = "db_people_id", type = "int", len = 10)
    private int id;

    @FieldLx(name = "db_people_name", type = "varchar", len = 100)
    private String name;

    @FieldLx(name = "db_people_age", type = "int", len = 10)
    private int age;

    public People() {
    }

    public People(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "People{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

//自定义注解：用作于类上
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableNameLx {
    String value();
}

//自定义注解：用作于列上
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldLx {
    String name();

    String type();

    int len();
}
